<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div>
        <h1>留言板</h1>
        <ul>

        </ul>
        标题：<input type="text" id="title"><br><br>
        内容：<textarea name="" id="con" cols="30" rows="10"></textarea><br>
        <button id="fb">发布</button>
    </div>
    <style>
        div {
            width: 700px;
            text-align: center;
            margin: auto;
        }

        h3 {
            color: bisque
        }

        p {
            font-size: 16px;
            color: cadetblue
        }

        span {
            font-size: 12px;
            color: darkgray
        }

        li {
            list-style: none;
            border-bottom: 1px solid #ccc;
        }
    </style>
</body>
<script>
    window.onload = function () {
    document.getElementById("fb").addEventListener("click", 
       function(){
        var t = document.getElementById("title").value
        console.log(t)
        var n = document.getElementById("con").value
        var tim=fun2()
        var obj={
            title:t,
            con:n,
            time:tim
        }
        fun(obj)
        fun1()    
       })
       fun1() 
    }
     //添加数据
     function fun(obj) {
        if (!localStorage.getItem('list')) {
            localStorage.setItem('list',JSON.stringify([obj]))
 
        }else{
            var data = JSON.parse(localStorage.getItem('list'))
            data.push(obj) 
            localStorage.setItem('list',JSON.stringify(data))  
        }
    }
//    获取列表
    function fun1() {    
        if (!localStorage.getItem('list')) {
            return
        }
       var data = JSON.parse(localStorage.getItem('list'))
        var str = ""
        for (item in data) {
            str += `<li>
                <h3>${data[item].title}</h3>
                <p>${data[item].con}</p>
                <span>${data[item].time}<a href="" onclick="del(${item})">删除</a></span></li>`
        }
        document.getElementsByTagName('ul')[0].innerHTML = str
      
    }
    //删除
    function del(index){
        var data = JSON.parse(localStorage.getItem('list'))
        data.splice(index,1)
        localStorage.setItem("list",JSON.stringify(data))
         fun1() 
    }
    //时间
    function fun2() {
        var date = new Date()
        var nian = date.getFullYear()
        var yue = date.getMonth() + 1
        var ri = date.getDate()
        var shi = date.getHours()
        var fen = date.getMinutes()
        var miao = date.getSeconds()
        return nian + "-" + yue + "-" + ri + "-" + shi + ":" + fen + ":" + miao
    }
       
</script>

</html>